<template>
  <div class="m-4">
    <BasicTable @register="registerTable">
      <template #toolbar>
        <a-button type="primary" @click="handleCreate"> 新增部门</a-button>
      </template>
      <template #bodyCell="{ column, record }">
        <template v-if="column.key === 'action'">
          <TableAction
            :actions="[
              {
                icon: 'clarity:note-edit-line',
                onClick: handleEdit.bind(null, record),
              },
              {
                icon: 'ant-design:delete-outlined',
                color: 'error',
                popConfirm: {
                  title: '是否确认删除',
                  placement: 'left',
                  confirm: handleDelete.bind(null, record.id),
                },
              },
            ]"
          />
        </template>
      </template>
    </BasicTable>
    <DeptModal @register="registerModal" @success="handleSuccess" />
  </div>
</template>
<script lang="ts" setup>
  import { BasicTable, TableAction, useTable } from '@/components/Table';
  import { doDeptDelete, getDeptList } from '@/modules/system/api';

  import { useModal } from '@/components/Modal';
  import DeptModal from './DeptModal.vue';
  import { ColumnPage } from './data';
  import { useMessage } from '@/hooks/web/useMessage';

  const { createMessage } = useMessage();

  defineOptions({ name: 'DeptManagement' });

  const [registerModal, { openModal }] = useModal();
  const [registerTable, { reload, deleteTableDataRecord }] = useTable({
    title: '部门列表',
    api: getDeptList,
    columns: ColumnPage,
    pagination: false,
    striped: false,
    useSearchForm: false,
    showTableSetting: true,
    bordered: true,
    showIndexColumn: false,
    canResize: true,
    actionColumn: {
      width: 120,
      title: '操作',
      dataIndex: 'action',
      fixed: 'right',
    },
  });

  function handleCreate() {
    openModal(true, {
      isUpdate: false,
    });
  }

  function handleEdit(record: Recordable) {
    openModal(true, {
      record,
      isUpdate: true,
    });
  }

  //delete
  function handleDelete(recordId: number) {
    doDeptDelete({ id: recordId }).then((res) => {
      if (res.code > 0) {
        createMessage.warning(res.message);
        return;
      }
      createMessage.success(res.message);
      deleteTableDataRecord(recordId);
    });
  }

  function handleSuccess() {
    reload();
  }
</script>
